package com.taotao.slink.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.google.common.base.Preconditions;
import com.taotao.common.BusinessException;
import com.taotao.common.RespData;
import com.taotao.common.redis.RedisClient;
import com.taotao.slink.model.dto.Captcha;
import com.taotao.slink.utils.SlinkRedisKeys;
import com.taotao.util.ValidatorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * </p>
 *
 * @author fanbeibei
 * @version 1.0.0
 * @date 2023/6/14 18:37
 */
@Service
public class CaptchaService {

    @Autowired
    private RedisClient redisClient;


    /**
     * 检查验证码是否正确
     *
     * @param captcha
     */
    public void checkVerifyCode(Captcha captcha) {
        Preconditions.checkArgument(null != captcha);
        ValidatorUtils.validateObj(captcha);

        String code = redisClient.get(SlinkRedisKeys.getLoginCaptchaKey(captcha.getClientCode()));
        if (null == code) {
            throw new BusinessException(RespData.VERIFY_CODE_ERROR, "验证码不正确");
        }

        if (!code.equalsIgnoreCase(captcha.getCaptcha())) {
            throw new BusinessException(RespData.VERIFY_CODE_ERROR, "验证码不正确");
        }

    }


    public void respLoginCaptcha(@RequestParam("clientCode") String clientCode, HttpServletResponse response) throws IOException {

        //创建验证码图片对象
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(100, 36, 4, 5);
        //获取验证码文本
        String code = captcha.getCode();
        //在控制台打印验证码方便以后自己登陆，直接复制即可。可不写
        System.err.println("验证码 ： " + code);
        //向session中存放验证码文本内容，用于接下来和用户填写的验证码对比
        redisClient.set(SlinkRedisKeys.getLoginCaptchaKey(clientCode), code, 2, TimeUnit.MINUTES);
        //创建输出流将验证码图片输出到浏览器上
        ServletOutputStream sos = response.getOutputStream();
        captcha.write(sos);
    }


}
